package ru.dc;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.Properties;
import java.util.Set;
import java.util.TreeSet;

/**
 * Реализация сервиса источников публичных хабов, основанная на java.util.Properties
 */
public class PublicHubServiceImpl implements PublicHubsService {

    private Log logger = LogFactory.getLog(getClass());
    private Set<String> hubs = new TreeSet<String>();
    /**
     * Имя файла, в котором будут храниться адреса источников, относительно директории приложения.
     */
    private static final String SOURCES_FILENAME = "public_hub_sources.properties";

    public void init() {
        File appDir = Application.getApplication().getApplicationHomeDir();
        File publicHubsList = new File(appDir, SOURCES_FILENAME);
        Properties p  = new Properties();
        try {
            p.load(new FileInputStream(publicHubsList));

            for (Object url : p.values()) {
                hubs.add(url.toString());
            }
        } catch (IOException e) {
            logger.error("Can't load public hubs sources", e);
        }
    }

    public void addSourceUrl(String url) {
        hubs.add(url);
        flush();
    }

    public void setSourceUrls(String... url) {
        hubs.clear();
        hubs.addAll(Arrays.asList(url));
        flush();
    }

    public void removeSourceUrl(String url) {
        hubs.remove(url);
        flush();
    }

    public Set<String> getSourceUrls() {
        return hubs;
    }

    /**
     * Сохраняет адреса в файле.
     */
    private void flush() {
        File appDir = Application.getApplication().getApplicationHomeDir();
        File publicHubsList = new File(appDir, SOURCES_FILENAME);
        Properties p  = new Properties();
        int i = 0;
        for (String url : hubs) {
            p.setProperty("source."+(i++), url);
        }
        try {
            p.store(new FileOutputStream(publicHubsList), "public hubs sources");
        } catch (IOException e) {
            logger.error("Can't store public hubs sources", e);
        }


    }
}
